package com.rich.paas.service.impl;

import com.alibaba.fastjson.JSON;
import com.rich.paas.namespace.RedisNamespace;
import com.rich.paas.service.WechatService;
import com.rich.paas.util.HttpXmlUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author chenhao
 * @version 1.0
 * @date 2018/6/10 下午2:34
 */
@Service
public class WechatServiceImpl implements WechatService {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 小程序appId
     */
    @Value("${wx.small_program.app_id}")
    public String smallProgramAppId;

    /**
     * 小程序appSecret
     */
    @Value("${wx.small_program.app_secret}")
    public String smallProgramAppSecret;

    /**
     * 登录凭证校验URL
     */
    private String codeVerifyUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
    /**
     * 获取AccessToken url
     */
    private String getAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET";

    @Override
    public String getAccessToken() throws IOException {
        //获取access_token
        String accessToken = (String) redisTemplate.opsForValue().get(RedisNamespace.WX_MP_ACCESS_TOKEN);
        if (StringUtils.isEmpty(accessToken)) {
            String url = getAccessTokenUrl;
            url = url.replace("APPID", smallProgramAppId)
                    .replace("SECRET", smallProgramAppSecret);
            String response = HttpXmlUtils.httpsRequest(url, "GET", null);
            logger.info("微信获取access_token接口返回:{}", response);
            accessToken = JSON.parseObject(response).getString("access_token");
            if (StringUtils.isEmpty(accessToken)) {
                throw new RuntimeException("获取access_token失败");
            }
            redisTemplate.opsForValue().set(RedisNamespace.WX_MP_ACCESS_TOKEN, accessToken, 7200, TimeUnit.SECONDS);
        }
        return accessToken;
    }

    @Override
    public String getOpenIdByCode(String code) throws IOException {
        String url = codeVerifyUrl;
        url = url.replace("APPID", smallProgramAppId)
                .replace("SECRET", smallProgramAppSecret)
                .replace("JSCODE", code);
        String response = HttpXmlUtils.httpsRequest(url, "GET", null);
        logger.info("微信获取openid接口返回:{}", response);
        String openId = JSON.parseObject(response).getString("openid");
        if (StringUtils.isEmpty(openId)) {
            throw new RuntimeException("登录凭证无效");
        }
        return openId;
    }
}